package utils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;
import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.type.JavaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import utils.commons.StringUtils;

public class JsonUtil {

	private static Logger log = LoggerFactory.getLogger(JsonUtil.class);
	
	static ObjectMapper om;
	
	public enum JSON_TYPE{
        /**JSONObject*/    
        JSON_TYPE_OBJECT,
        /**JSONArray*/
        JSON_TYPE_ARRAY,
        /**不是JSON格式的字符串*/
        JSON_TYPE_ERROR
    }

	public static String parseObject(final Object object) {
		if(om==null){
			om = new ObjectMapper();
		} 
		String ret=null;
		try {
			ret=om.writeValueAsString(object);
		} catch (Exception e) {
			log.error("对象转换json字符串失败", e);
		}
		return ret;
	}
	public static  Object readJson2Entity(String jsonstr,Class<?> oclass){
		try {
			if(om==null){
				om = new ObjectMapper();
			} 
	        Object acc = om.readValue(jsonstr, oclass);
	        return acc;
	    } catch (Exception e) {
	    	log.error("json字符串转换对象失败", e);
	    }
		return null;
	}
	
	/**
	 * @author ldl
	 * 把json字符串转化为Map对象
	 * @param string
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public static Map paseJson2Map(String string) throws Exception{
		try {
			if(om==null){
				om = new ObjectMapper();
			} 
			return om.readValue(string, Map.class);
		} catch (Exception e) {
			throw new  Exception(e.getMessage());
		}
	}
	
	public static JsonNode getJsonNode(String orgstr) throws IOException{
		if(om==null){
			om = new ObjectMapper();
		} 
        try {
        	JsonNode jn = om.readTree(orgstr);
        	return jn;
        } catch (IOException e) {
            throw e;
        }
	}
	
	
	
	/***
     * 
     * 获取JSON类型
     *         判断规则
     *             判断第一个字母是否为{或[ 如果都不是则不是一个JSON格式的文本
     *         
     * @param str
     * @return
     */
    public static JSON_TYPE getJSONType(String str){
        if(StringUtils.isNotEmptyString(str)){
        	 final char[] strChar = str.substring(0, 1).toCharArray();
             final char firstChar = strChar[0];
                          
             if(firstChar == '{'){
                 return JSON_TYPE.JSON_TYPE_OBJECT;
             }else if(firstChar == '['){
                 return JSON_TYPE.JSON_TYPE_ARRAY;
             }else{
                 return JSON_TYPE.JSON_TYPE_ERROR;
             }
        }else{
        	return JSON_TYPE.JSON_TYPE_ERROR;
        }        
    }
	
	public static List<Map<String, Object>> parsestr2list(String orgstr) throws IOException{
		if(om==null){
			om = new ObjectMapper();
		} 
        try {
        	/*JsonGenerator jsonGenerator =  om.getJsonFactory().
        			createJsonGenerator(System.out, JsonEncoding.UTF8);*/
        	List<Map<String, Object>> list = om.readValue(orgstr, List.class);
        	return list;
        } catch (IOException e) {
            throw e;
        }
		
	}
	
	
	public static String[] parsestr2arrstr(String orgstr) throws IOException{
		if(om==null){
			om = new ObjectMapper();
		} 
        try {
        	/*JsonGenerator jsonGenerator =  om.getJsonFactory().
        			createJsonGenerator(System.out, JsonEncoding.UTF8);*/
        	String[] arr = om.readValue(orgstr, String[].class);
        	return arr;
        } catch (IOException e) {
            throw e;
        }
		
	}
	
	/**
	 * @param object 要转化的对象
	 * @param pattern 格式化的模式 如:"yyyy-MM-dd HH:mm:ss"
	 * @return
	 */
	public static String parseObject(final Object object, String pattern) {
		SimpleDateFormat sdf=new SimpleDateFormat(pattern);
		if(om==null){
			om = new ObjectMapper();
		} 
		om.setDateFormat(sdf);
		String ret=null;
		try {
			ret=om.writeValueAsString(object);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}
	/**
	 * 把一个对象转化为json字符串
	 * @param object 被转化的对象
	 * @return
	 */
	public static String parsePojoObject(final Object object) throws Exception{
		if(om==null){
			om = new ObjectMapper();
		} 
		String ret = om.writeValueAsString(object);
		return ret;
	}
	/**
	 * 如果有继承关系，把对象转化为json时加入过滤字段则只会把对应对象的属性进行转化
	 * @param object 被转化的对象
	 * @param filterob 对象的JsonFilter值
	 * @param specifypro 指定要转化的字段
	 * @return
	 */
	public static String parseObject(final Object object, final String filterob,final String[] specifypro) throws Exception{
		if(om==null){
			om = new ObjectMapper();
		} 
		SimpleFilterProvider filter = new SimpleFilterProvider().setFailOnUnknownId(false);
		filter.addFilter(filterob, SimpleBeanPropertyFilter.filterOutAllExcept(specifypro));
		om.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
		om.setFilters(filter);
		String ret = om.writeValueAsString(object);
		return ret;
	}
	/**
	 * 如果要转化的对象有多个JsonFilter值时采用
	 * @param object 被转化的对象
	 * @param filterMap 对象的JsonFilter值和过滤属性的map集合
	 * @param dateFormat 对日期类型进行格式化
	 * @return 转化后的json字符串
	 */
	public static String parseObject(Object object,Map<String, String[]> filterMap,String dateFormat) throws Exception{
		if(om==null){
			om = new ObjectMapper();
		} 
		SimpleDateFormat format = new SimpleDateFormat(dateFormat);
		om.setDateFormat(format);
		SimpleFilterProvider filter = new SimpleFilterProvider().setFailOnUnknownId(false);
		for (Map.Entry<String, String[]> mapItem : filterMap.entrySet()) {
			filter.addFilter(mapItem.getKey(), SimpleBeanPropertyFilter.filterOutAllExcept(mapItem.getValue()));
		}
		om.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
		om.setFilters(filter);
		String ret=null;
		ret=om.writeValueAsString(object);
		return ret;
	}
	/**
	 * 如果要转化的对象有多个JsonFilter值时采用
	 * @param object 被转化的对象
	 * @param filterMap 对象的JsonFilter值和过滤属性的map集合
	 * @return 转化后的json字符串
	 */
	public static String parseObject(Object object,Map<String, String[]> filterMap) throws Exception{
		if(om==null){
			om = new ObjectMapper();
		} 
		SimpleFilterProvider filter = new SimpleFilterProvider().setFailOnUnknownId(false);
		for (Map.Entry<String, String[]> mapItem : filterMap.entrySet()) {
			filter.addFilter(mapItem.getKey(), SimpleBeanPropertyFilter.filterOutAllExcept(mapItem.getValue()));
		}
		om.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
		om.setFilters(filter);
		String ret = om.writeValueAsString(object);
		return ret;
	}
		
	public static  List<?> paseJson2Collection(String string,Class<?> x) throws Exception{  
		if(om==null){
			om = new ObjectMapper();
		} 
        JavaType javaType = getCollectionType(ArrayList.class, x); 
        List<Class<?>> list =  (List<Class<?>>)om.readValue(string, javaType); 
        return list;
    }   
	
	/**
	 * @author ldl
	 * 把json字符串转化为Map对象
	 * @param string
	 * @return
	 * @throws Exception
	 */
	public static LinkedHashMap paseJson2LinkedHashMap(String string) throws Exception{
		if(om==null){
			om = new ObjectMapper();
		} 
		return om.readValue(string, LinkedHashMap.class);
	}
       /**   
        * 获取泛型的Collection Type  
        * @param collectionClass 泛型的Collection   
        * @param elementClasses 元素类   
        * @return JavaType Java类型   
        * @since 1.0   
        */   
    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses)  throws Exception{   
    	if(om==null){
			om = new ObjectMapper();
		} 
        return om.getTypeFactory().constructParametricType(collectionClass, elementClasses);   
    }
    
    /**
     * 把指定对象转换为json字符串
     * Map<String,Object>中Object为业务实体或者单个属性
     * @param list
     * @param filtermap
     * @return
     * @throws Exception
     */
    public static String parseAssignObject2String(List<Map<String, Object>> list,Map<String, String[]> filtermap) throws Exception {
    	return parseObject(list, filtermap);
    }
	
    
    public static String formatJSONP(String jsonstr, String callback){
    	return callback + "(" + jsonstr + ")";
    }
    

}
